package org.sky.sys.util;

import org.sky.util.JsonUtils;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author weifx
 * @Title: RequestUtils
 * @ProjectName springboot-platform
 * @Description: TODO{Request工具类}
 * @date 2019/3/6 22:29
 * @Version 1.0
 */
public class RequestUtils {
    /**
     * 获取类的所有属性
     * @param list
     * @param clazz
     * @return
     */
    public static List<Field> getAllField(List<Field> list, Class clazz){
        if(!clazz.equals(Object.class)){
            Field[] f=clazz.getDeclaredFields();
            for(int i=0;i<f.length;i++){
                list.add(f[i]);
            }
            getAllField(list,clazz.getSuperclass());
        }
        return list;
    }
    /**
     * 从请求中获取对象
     * @param request
     * @param clazz
     * @return
     */
    public static <T> T getEntityBean(HttpServletRequest request, Class<T> clazz){
        List<Field> idField = new ArrayList();
        idField=getAllField(idField, clazz);
        Map js= new HashMap();
        for (Field field : idField) {
            String name = field.getName();
            String str = request.getParameter(name);
            if(str != null){
                js.put(name, str);
            }
        }
        return JsonUtils.map2pojo(js, clazz);
    }
}
